<script setup>
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter } from "vue-router";
import { printInfo } from '@/util/log';
import { ref, computed, onMounted } from 'vue'
const store = useStore()
const router = useRouter()
const isLoggedIn = computed(() => !!store.state.Authorization)

const videoData = ref([])

const dialogVisible = ref(false)

async function getVideoList() {
  try {
    const result = await axios.get(import.meta.env.VITE_API_HOST + '/db.php?dbType=getAll')
    videoData.value = result.data.banner
  } catch(error) {
    console.log(error)
  }
}
getVideoList()

function delbanner(id) {
  axios.get(import.meta.env.VITE_API_HOST + '/db.php?dbType=delBanner&id=' + id)
  .then(function (response) {
    if (response.data.code == 200) {
      ElMessage.success('操作成功')
      getVideoList()
    } else {
      ElMessage.error('操作失败')
    }
  })
  .catch(function (error) {
    console.log(error)
    ElMessage.error('操作失败')
  })
}

import { Plus } from '@element-plus/icons-vue'

const imageUrl = ref('')

const uploadImg = ref('')

const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
}
const input = ref('')
const input1 = ref('')
async function uploadfm(file, fileList) {
  console.log(fileList)
  const formData = new FormData();
  formData.append("file[]", file.file);
  try {
    const result = await axios.post(import.meta.env.VITE_API_HOST + '/uploadbanner.php', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    uploadImg.value = './' + result.data[0].path
    return result.data
  }catch (e) {
    console.log(e)
    ElMessage.error("上传错误")
  }
}

function beforeAvatarUpload(file) {
  const accept = "png,jpg,jpeg"
  const isFileTypeIf = accept.split(',').includes(`${file.name.split('.').pop().toLowerCase()}`)
  if (!isFileTypeIf) {
    ElMessage.error("文件格式错误")
  }
  console.log(isFileTypeIf, file)
  return isFileTypeIf
}

async function handleUpload() {
  const url = `${import.meta.env.VITE_API_HOST}/db.php?dbType=addBanner&title=${encodeURIComponent(input.value)}&link=${encodeURIComponent(input1.value)}&path=${encodeURIComponent(uploadImg.value)}`
  try {
    const result = await axios.post(url)
    if (result.data.code === 200) {
      ElMessage({
        message: '添加成功',
        type: 'success'
      })
      dialogVisible.value = false
    } else {
      ElMessage({
        message: '添加失败',
        type: 'error'
      })
      dialogVisible.value = false
    }
    getVideoList()
  } catch (error) {
    console.log(error)
  }
}
onMounted(() => {
  if (isLoggedIn.value) {
    printInfo({ title: "登录成功", text: "欢迎回来", type: "success", plain: true });
  } else {
    printInfo({ title: "登录失败", text: "请检查你的登录信息", type: "error", plain: true });
    router.push("/login");
    store.dispatch('logout');
  }
})
</script>

<template>
  <el-card style="max-width: 100%" shadow="never">
    <template #header>
      <div class="card-header">
        <span>轮播图管理</span>
      </div>
    </template>
    <el-button type="primary" @click="dialogVisible='true';"><el-icon><UploadFilled /></el-icon>添加轮播图</el-button><br><br>
    <el-table :data="videoData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="100px" align="center"/>
      <el-table-column align="center" label="轮播图" width="200px">
          <template #default="{ row }">
            <el-image
              :preview-teleported="true"
              :src="'http://192.168.44.1/dmcy/' + row?.path"
              style="width: 160px; height: 120px"
            />
          </template>
      </el-table-column>
      <el-table-column prop="title" label="名称" min-width="200px" align="center"/>
      <el-table-column label="操作" min-width="190px" align="center">
        <template #default="{ row }">
          <el-button type="danger" @click="delbanner(row.id)"><el-icon><Delete /></el-icon>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <el-dialog v-model="dialogVisible" title="轮播图上传" width="500" draggable>
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="uploadfm"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload><br>
    <el-input
      v-model="input"
      style="width: 240px"
      placeholder="标题"
      clearable
    /><br><br>
    <el-input
      v-model="input1"
      style="width: 240px"
      placeholder="跳转的链接"
      clearable
    /><br><br>
    <el-button type="primary" @click="handleUpload"><el-icon><UploadFilled /></el-icon>上传</el-button>
  </el-dialog>
</template>
<style>
:deep(.el-image) {
  img {
    object-fit: cover;
  }
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
